package api

import (
	"blogdemo/gin/errmsg"
	"blogdemo/gin/model"
	"github.com/gin-gonic/gin"
)

type NewPasswd struct {
	Username    string `gorm:"type:varchar(20); not null" json:"username"`
	PhoneNumber string `gorm:"type:varchar(11); not null" json:"phoneNumber"`
	Password    string `gorm:"type:varchar(20); not null" json:"password"`
	Nd          string `gorm:"type:varchar(20); not null" json:"newPass"`
	Sd          string `gorm:"type:varchar(20); not null" json:"surePass"`
}

func UpdatePassword(c *gin.Context) {
	var user model.User
	var npd NewPasswd
	// 绑定数据模型
	//_ = c.ShouldBind(&user)
	_ = c.ShouldBind(&npd)
	user.Username = npd.Username
	user.Password = npd.Password
	println("new password:" + npd.Nd)

	checkpass := model.CheckLogin(user.Username, user.Password)
	if checkpass != errmsg.SUCCESS {
		c.JSON(400, gin.H{
			"status": errmsg.PASSWORD_WRONG,
			"data1":  user,
			"data2":  npd,
			"msg":    errmsg.GetErrMsg(errmsg.PASSWORD_WRONG),
		})
		c.Abort()
		return
	}

	if npd.Nd == user.Password {
		c.JSON(400, gin.H{
			"status": errmsg.PASSWORD_SAME,
			"data1":  user,
			"data2":  npd,
			"msg":    errmsg.GetErrMsg(errmsg.PASSWORD_SAME),
		})
		c.Abort()
		return
	}

	if !model.CheckPassword(npd.Nd) {
		c.JSON(400, gin.H{
			"status": errmsg.PASSWORD_INVALID,
			"data1":  user,
			"data2":  npd,
			"msg":    errmsg.GetErrMsg(errmsg.PASSWORD_INVALID),
		})
		c.Abort()
		return
	}

	if npd.Sd != npd.Nd {
		c.JSON(400, gin.H{
			"status": errmsg.NNUMBER_DIFF,
			"data1":  user,
			"data2":  npd,
			"msg":    errmsg.GetErrMsg(errmsg.NNUMBER_DIFF),
		})
		c.Abort()
		return
	}

	user.Password = npd.Nd
	uppwd := model.UpPassword(user)
	if uppwd == errmsg.SUCCESS {
		c.JSON(200, gin.H{
			"status": errmsg.SUCCESS,
			"data1":  user,
			"data2":  npd,
			"msg":    errmsg.GetErrMsg(errmsg.SUCCESS),
		})
	} else {
		c.JSON(400, gin.H{
			"status": errmsg.FAIL,
			"data1":  user,
			"data2":  npd,
			"msg":    errmsg.GetErrMsg(errmsg.FAIL),
		})
	}

}
